//
//  PassengerInput.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/10.
//

import Foundation

class PassengerInput : ObservableObject {
  @Published var laosMobile : String = ""
  @Published var wechatNo   : String = ""
  var gender : Bool = true
  var mobile : String = ""
  var name : String = ""

  // 读取或者初始化
  func read() -> Passenger? {
    let data = UserDefaults.standard.string(forKey: "Passenger")
    if let d = data {
      let coder = JSONDecoder()
      let p = try? coder.decode(Passenger.self,from:Data(d.utf8))
      return p!
    }
    return Passenger(openId:"", name: "", isMale: true, mobile: "", laosMobile: "",wechatNo: "")
  }

  // 保存个人信息
  func save(info: Passenger) {
    let encoder = JSONEncoder()
    if let data = try? encoder.encode(info) {
      UserDefaults.standard.set(String(decoding: data, as: UTF8.self), forKey: "Passenger")
      UserDefaults.standard.synchronize()

       Api.savePassengerInfo(passengerInfo: info) { r in
          switch r {
             case .success(let data):
                logger.info("savePassengerInfo result:\(data)")
             case .failure(let err):
                logger.info("savePassengerInfo error:\(err.localizedDescription)")
          }
       }
    } else {
      print("Save passenger info failure.")
    }
  }
}
